package org.datascooter.generator;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.datascooter.DataScooter;
import org.datascooter.bundle.DSMapper;
import org.datascooter.bundle.EntityBundle;
import org.datascooter.bundle.attribute.AbstractAttribute;
import org.datascooter.bundle.attribute.PersistAttribute;
import org.datascooter.exception.EntityNotMappedException;
import org.datascooter.inface.IIdGenerator;
import org.datascooter.utils.LangUtils;

public class ContextIdGenerator implements IIdGenerator<String> {

	private List<PersistAttribute> attributes = new ArrayList<PersistAttribute>();

	public ContextIdGenerator(List<PersistAttribute> attributes) {
		this.attributes = attributes;
	}

	public ContextIdGenerator(String entity, String... attributeNames) throws EntityNotMappedException, SecurityException, NoSuchMethodException {
		this(entity, Arrays.asList(attributeNames));
	}

	public ContextIdGenerator(String entity, List<String> attributesName) throws EntityNotMappedException, SecurityException, NoSuchMethodException {
		EntityBundle bundle = DSMapper.getBundle(entity);
		for (String attribute : attributesName) {
			attributes.add(bundle.getAttribute(attribute));
		}
	}

	@Override
	public String getId(Object value) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
		Long result = 0L;
		for (AbstractAttribute attribute : attributes) {
			Object object;
			object = attribute.getValue(value);
			if (object != null) {
				result += object.hashCode();
			}
		}
		String ids = "x" + result;
		return LangUtils.overlay(DataScooter.ID, ids, 36 - ids.length(), 36);
	}
}
